package pnu.ssm.service;

import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import pnu.ssm.appinfo.AppInfo;
import pnu.ssm.appinfo.AppListHelper;
import pnu.ssm.http.HttpConnector;
import pnu.ssm.key.Key;
import pnu.ssm.sbchild.MainActivity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class AppProtectService extends Service {

	public static final String TAG = "AppProtectService";
	
	private final int breakTime = 5000; // 5초
	
	private static final int ONE_MIN = 1000 * 60;
	private static final int START_CHECKER = 0; 
	
	public static boolean enabled = true;
	
	private ActivityManager activityManager;
	private AppListHelper appListHelper = AppListHelper.getInstance();
	private Timer timer;
	
	private HttpConnector httpConnector;
	
	private SharedPreferences pref;
	private SharedPreferences.Editor editor;
	
	
	AppListHelper helper = AppListHelper.getInstance();
	
	Object lock = new Object();
	
	Handler appProtectServiceHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			case START_CHECKER:
				String obtain_time = pref.getString(Key.obtain_time, "0");
				Toast.makeText(getApplicationContext(), "You can use this app for : "+ 1 + "min", Toast.LENGTH_SHORT).show();

				Timer notifier = new Timer();
				notifier.schedule(new TimerTask() {
					@Override
					public void run() {
						synchronized (lock) {
							lock.notifyAll();
						}
					}
				}, ONE_MIN);
				
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void onCreate() {
		super.onCreate();
		
		Log.i(TAG, "onCreate()");
		
		activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
		timer = new Timer();
		
		pref = getApplicationContext().getSharedPreferences(Key.prefKey, Context.MODE_PRIVATE);
		editor = pref.edit();
		
		httpConnector = HttpConnector.getInstance();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		
		Log.i(TAG, "onDestroy()");
		
		Intent intent = new Intent();
		intent.setAction("pnu.ssm.intent.action.die.AppProtectService");
		
		sendBroadcast(intent);
		
		if(timer != null)
			timer.cancel();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		
		Log.d(TAG, "onStartCommand()");
		
		timer.scheduleAtFixedRate(new AppProtectSchedule(), 0, breakTime);
		
		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	class AppProtectSchedule extends TimerTask {
		
		@Override
		public void run() {
			Log.d(TAG, "AppProtectService is running");
			String child_num = pref.getString(Key.child_num, "0");
			String obtain_time = pref.getString(Key.obtain_time, "0");
			int obtain_time_int = Integer.parseInt(obtain_time);
			
			List<AppInfo> forbiddenAppList = httpConnector.getForbiddenAppList(child_num);
			List<RunningTaskInfo> appList = activityManager.getRunningTasks(1);
			
			Iterator<RunningTaskInfo> taskIter = appList.iterator();
			while(taskIter.hasNext()){
				RunningTaskInfo taskInfo = taskIter.next();
				
				ComponentName componentName = taskInfo.baseActivity;
				String currentTaskPackageName = componentName.getPackageName();
				Iterator<AppInfo> forbiddenIter = forbiddenAppList.iterator();
				
				while(forbiddenIter.hasNext()){
					AppInfo appInfo = forbiddenIter.next();
					String forbiddenPackageName = appInfo.getPackageName();
					
					if(currentTaskPackageName.equalsIgnoreCase(forbiddenPackageName)) {
						//if(obtain_time_int > 0){
						if (!enabled) {
							obtain_time_int--;
//							String child_num = pref.getString(Key.child_num, "");
							editor.putString(Key.obtain_time, "" + obtain_time_int);
							editor.commit();
							
							//httpConnector.sendChineseState(child_num, ""+obtain_time_int);
							try {
								Log.i(TAG, "Start time checker");
								synchronized (lock) {
									appProtectServiceHandler.sendEmptyMessage(START_CHECKER);
									lock.wait();
									enabled = true;
								}
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						} else {
							Log.i(TAG, "Start MainActivity");
							Intent i = new Intent(getBaseContext(),MainActivity.class);
							i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
							startActivity(i);
						}
					}
				}
			}
		}
	}
}
